package io.gitee.zhangbinhub.acp.boot.integration

import io.gitee.zhangbinhub.acp.boot.*
import org.noear.snack4.Feature
import org.noear.solon.core.AppContext
import org.noear.solon.core.Plugin
import org.noear.solon.core.util.RunUtil
import org.noear.solon.scheduling.annotation.Scheduled
import org.noear.solon.scheduling.scheduled.manager.IJobManager
import org.noear.solon.scheduling.scheduled.manager.JobExtractor
import org.noear.solon.scheduling.simple.JobManager
import org.noear.solon.serialization.snack4.Snack4StringSerializer

class XPluginImp : Plugin {
    override fun start(context: AppContext) {
        context.beanMake(AcpBootLogAutoConfiguration::class.java)
        context.beanMake(AcpBootCorsAutoConfiguration::class.java)
        context.beanMake(AcpBootComponentAutoConfiguration::class.java)
        context.beanMake(AcpBootInfoAutoConfiguration::class.java)
        context.beanMake(AcpBootSetUpAutoConfiguration::class.java)
        context.beanMake(AcpBootAutoConfiguration::class.java)
        context.lifecycle(Int.MIN_VALUE) {
            context.getBean(Snack4StringSerializer::class.java)?.apply {
                this.serializeConfig.addFeatures(Feature.Write_EnumUsingName)
                this.deserializeConfig.addFeatures(Feature.Write_EnumUsingName)
            }
        }
        initScheduled(context)
    }

    private fun initScheduled(context: AppContext) {
        JobManager.getInstance().let { jobManager ->
            //预热线程池
            RunUtil.preheat()
            //注册 IJobManager
            context.wrapAndPut(IJobManager::class.java, jobManager)
            //提取任务
            val jobExtractor = JobExtractor(jobManager)
            context.beanBuilderAdd(Scheduled::class.java, jobExtractor)
            context.beanExtractorAdd(Scheduled::class.java, jobExtractor)
            //容器加载完后，再启动任务
            context.lifecycle(Int.MAX_VALUE, jobManager)
        }
    }

    override fun stop() {
        JobManager.getInstance().let { jobManager ->
            if (jobManager.isStarted) {
                jobManager.stop()
            }
        }
    }
}